package cn.kgc.vue.service.impl;

import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Dept;
import cn.kgc.vue.entity.User;
import cn.kgc.vue.mapper.DeptMapper;
import cn.kgc.vue.mapper.UserMapper;
import cn.kgc.vue.service.DeptService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author mengshun
* @description 针对表【sys_dept】的数据库操作Service实现
* @createDate 2024-07-03 14:20:13
*/
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService{


    @Resource
    private UserMapper userMapper;

    @Override
    public ResponseResult deptPage(QueryCondition<Dept> queryCondition) {

        Page<Dept> deptPage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());
        String deptName = queryCondition.getSearchParams().getDeptName();

        LambdaQueryWrapper<Dept> lambda = new QueryWrapper<Dept>().lambda();
        lambda.like(StringUtils.isNotBlank(deptName),Dept::getDeptName,deptName)
                .orderByDesc(Dept::getCreateTime);

        baseMapper.selectPage(deptPage,lambda);


        return ResponseResult.success().data("total",deptPage.getTotal()).data("tableData",deptPage.getRecords());
    }

    @Override
    public ResponseResult delete(Integer id) {
        // 删除之前 查询当前部门是否存在员工

        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getDeptId,id) ;


        List<User> users = userMapper.selectList(lambda);
        if (ObjectUtils.isNotNull(users)){
            return  ResponseResult.fail().message("该部门存在员工,不能删除");
        }

        baseMapper.deleteById(id);
        return ResponseResult.success().message("删除成功");
    }
}




